/**
 * @file
 * @author dousha 
 * @date 2021/4/22.
 */

#include "storage.h"
#include "stm32f1xx_hal.h"
#include "system.h"

static I2C_HandleTypeDef *hwnd = NULL;
static uint8_t storagePresent = 0;

static void storage_seek(uint16_t pos) {
	uint8_t buf[2];
	buf[0] = (pos >> 8);
	buf[1] = (pos & 0xffu);
	HAL_I2C_Master_Transmit(hwnd, EEPROM_ADDR, buf, 2, HAL_MAX_DELAY);
}

extern void storage_init(I2C_HandleTypeDef *handle) {
	hwnd = handle;
	if (!HAL_I2C_IsDeviceReady(hwnd, EEPROM_ADDR, 5, 5)) {
		return;
	}
	system_mark_module_ready(MODULE_STORAGE);
	storagePresent = 1;
}

extern size_t storage_read(uint8_t *out, uint16_t offset, uint16_t size) {
	if (storagePresent) {
		storage_seek(offset);
		HAL_I2C_Master_Receive(hwnd, EEPROM_ADDR, out, size, HAL_MAX_DELAY);
		return size;
	} else {
		return 0;
	}
}

extern size_t storage_write(const uint8_t *in, uint16_t offset, uint16_t size) {
	if (storagePresent) {
		uint8_t buf[3] = { 0 };
		for (uint16_t i = 0; i < size; i++) {
			buf[0] = (i >> 8);
			buf[1] = (i & 0xffu);
			buf[2] = in[offset + i];
			HAL_I2C_Master_Transmit(hwnd, EEPROM_ADDR, buf, 3, HAL_MAX_DELAY);
		}
		return size;
	} else {
		return 0;
	}
}
